package com.lxz.jucdemo.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 刘新智
 * @Date: 2025/10/25 12:29
 * @Description:
 * @Version: v1.0
 */
public class ProductConsumeTest2{
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"D").start();
    }

}

class Data2{
    private int number;

    Lock lock=new ReentrantLock();


    /**
     * 1.Condition 是 Java 并发包中用于线程间协调通信的工具，
     * 它必须配合 Lock 使用，作用类似于传统的 wait()/notify() 机制，但功能更强大、更灵活。
     *
     * 2.Condition 允许线程在某个条件不满足时等待，并在条件满足时被其他线程唤醒，实现线程间的协作。
     * */
    Condition condition=lock.newCondition();

    public void increment() throws InterruptedException {
        try {
            lock.lock();
            while (number != 0) {
                condition.await();// 等待
            }
            number++; // 业务代码
            System.out.println(Thread.currentThread().getName() + ":" + number);
            condition.signalAll();// 唤醒
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void decrement(){
        try {
            lock.lock();
            while (number == 0) {
                condition.await();// 等待
            }
            number--;// 业务代码
            condition.signalAll(); // 唤醒
            System.out.println(Thread.currentThread().getName() + ":" + number);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
